<template>
	<view class="comment-page">
		<scroll-view scroll-y="true" @scrolltolower="loadMoreComments" class="comment-list">
			<view class="tab-bar">
				<view v-for="tab in tabs" :key="tab.value" class="tab" :class="{ active: activeTab === tab.value }"
					@tap="setActiveTab(tab.value)">
					{{ tab.name }}({{ tab.count }})
				</view>
			</view>

			<view class="comment-list">
				<view v-for="(comment, index) in comments" :key="index" class="comment-item">
					<view class="user-info">
						<image :src="loadUrl + comment.photo" class="user-avatar"></image>
						<view class="user-details">
							<text class="username">{{ comment.nickname }}</text>
							<view class="rating">
								<text v-for="i in 5" :key="i"
									:class="['star', { filled: i <= comment.rating }]">★</text>
							</view>
						</view>
					</view>
					<view class="comment-content">{{ comment.reviewText }}</view>
					<view class="image-container" v-if="comment.images && comment.images.length">
						<image v-for="(img, imgIndex) in comment.images" :key="imgIndex" :src="img" mode="aspectFill"
							class="comment-image" @tap="previewImage(comment.images, imgIndex)"></image>
					</view>
					<view class="comment-meta">
						<text class="date">{{ formatDate(comment.createdAt) }}</text>
					</view>
				</view>

				<view v-if="loading" class="loading">
					<text>加载中...</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
	    data() {
	        return {
	            activeTab: 'all',
	            tabs: [
	                { name: '全部', value: 'all', count: 0 },
	                { name: '最新', value: 'latest', count: 0 },
	                { name: '好评', value: 'favorable', count: 0 },
	                { name: '中评', value: 'moderate', count: 0 },
	                { name: '差评', value: 'negative', count: 0 },
	                { name: '有图', value: 'withPicture', count: 0 }
	            ],
	            comments: [],
	            page: 1,
	            pageSize: 10,
	            loading: false,
	            itemId: null ,// 用于存储商品 ID,
				loadUrl: this.$loadUrl
	        }
	    },
	    onLoad(options) {
	        // 从页面参数中获取商品 ID
	        if (options.itemId) {
	            this.itemId = options.itemId;
	            this.loadComments(); // 加载评论
	        } else {
	            console.error('缺少商品 ID');
	            uni.showToast({
	                title: '商品 ID 不存在',
	                icon: 'none'
	            });
	        }
	    },
	    methods: {
	        setActiveTab(tab) {
	            this.activeTab = tab;
	            this.resetAndReload();
	        },
	        resetAndReload() {
	            this.page = 1;
	            this.comments = [];
	            this.loadComments();
	        },
	        loadComments() {
	            if (this.loading) return;
	            this.loading = true;
	
	            console.log('当前商品ID:', this.itemId); // 打印商品 ID
	
	            this.$service({
	                url: `/reviews/item/` + this.itemId,
	                method: 'GET',
	                data: {
	                    page: this.page,
	                    pageSize: this.pageSize,
	                    type: this.activeTab
	                }
	            }).then(res => {
	                if (res.code === 0) {
	                    this.comments = Array.isArray(res.data) ? [...this.comments, ...res.data] : this.comments;
	                    console.log(this.comments)
						this.tabs = this.tabs.map(tab => ({
	                        ...tab,
	                        count: res.data.counts ? res.data.counts[tab.value] || 0 : 0
	                    }));
	                    this.page++; // 确保页数增加
	                } else {
	                    throw new Error(res.message || '加载评论失败');
	                }
	            }).catch(error => {
	                console.error('加载评论失败', error);
	                uni.showToast({
	                    title: error.message || '加载评论失败，请稍后重试',
	                    icon: 'none'
	                });
	            }).finally(() => {
	                this.loading = false; // 确保无论成功失败都停止loading状态
	            });
	        },
	        loadMoreComments() {
	            this.loadComments();
	        },
	        formatDate(dateString) {
	            const date = new Date(dateString);
	            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
	        },
	        previewImage(images, current) {
	            uni.previewImage({
	                urls: images,
	                current: current
	            });
	        }
	    }
	}
</script>

<style scoped>
	.comment-page {
		padding: 20rpx;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.tab-bar {
		display: flex;
		overflow-x: auto;
		margin-bottom: 20rpx;
		background-color: #fff;
		padding: 10rpx;
		border-radius: 10rpx;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 15rpx 0;
		font-size: 24rpx;
		color: #666;
		transition: all 0.3s;
	}

	.tab.active {
		background-color: #ff6b81;
		color: #fff;
		border-radius: 30rpx;
	}

	.comment-list {
		height: calc(100% - 180rpx);
	}

	.comment-item {
		background-color: #fff;
		margin-bottom: 20rpx;
		padding: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.user-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.user-details {
		flex: 1;
	}

	.username {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.rating {
		margin-top: 5rpx;
	}

	.star {
		color: #ddd;
		font-size: 24rpx;
	}

	.star.filled {
		color: #ffb400;
	}

	.comment-content {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 15rpx;
	}

	.image-container {
		display: flex;
		flex-wrap: wrap;
	}

	.comment-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
		border-radius: 8rpx;
	}

	.comment-meta {
		color: #999;
		font-size: 24rpx;
		text-align: right;
	}

	.loading {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}
</style>
